import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sph_shipper/AppConfig/CityLIstData.dart';
import 'package:sph_shipper/AppConfig/Config.dart';
import 'package:sph_shipper/AppConfig/LocalStorage.dart';
import 'package:sph_shipper/SendGoods/CargoInformation.dart';
import 'package:sph_shipper/SendGoods/PerfectGoods.dart';
import 'package:sph_shipper/SendGoods/PublishEnterpriseGoods.dart';

import '../AppConfig/RouteAct.dart';
import '../http/CityHttp.dart';
import '../http/NoLoadingGetApi.dart';
import '../http/api.dart';
import '../l10n/messages.dart';
import 'LoadingAddressView.dart';
import 'package:http/http.dart' as http;
class AddGoodsFirst extends StatefulWidget {
  const AddGoodsFirst({super.key, required this.dataMap, required this.editType});
  final Map dataMap;
  //1.发货 2.编辑 3.再发一单 4.编辑常发货源
  final int editType;
  @override
  State<AddGoodsFirst> createState() => _AddGoodsFirstState();
}

class _AddGoodsFirstState extends State<AddGoodsFirst> {


  late List<bool> isSelectedList;

  @override

  int sendType=1;

  bool isAddStart = false;
  bool isAddEnd = false;
  String goodsMessage = "";
  String parentDictValue = "";
  List carLength=[];

  List carType=[];
  List? goodsMessageList;
  int invoiceType = 1;

  String startCitynameOne ="";
  List startCitycodeOne =[];
  String startCitynameTwo ="";
  List startCitycodeTwo =[];
  String endCitynameOne ="";
  List endCitycodeOne =[];
  String endCitynameTwo ="";
  List endCitycodeTwo =[];
  String selectedProvince = '';
  String selectedCity = '';
  String selectedDistrict = '';
  String selectedCityCode = '';
  List startAddressOne=[];
  List startAddressTwo=[];
  List endAddressOne=[];
  List endAddressTwo=[];
  List cityData = [];

  String storedData = '';
  int selectedTileIndexone=-1;
  int selectedTileIndextwo=-1;
  int selectedTileIndexthree=-1;
  String detailAddressOne="";
  String detailAddressTwo="";
  String detailAddressThree="";
  String detailAddressFour="";
  Map startLocationOne={};
  Map startLocationTwo={};
  Map endLocationOne={};
  Map endLocationTwo={};
  String dintanceStr="";
  int titleType=1;
  String companyName="";
  void initState() {
    super.initState();
    // isSelectedList = List.generate(carTypeList.length, (index) => false);
    getUserInfo();
    // getCityList();
    // cityData=MyCityListData.CityList;
    print(widget.dataMap);
    print(widget.dataMap['deposit']);
    if (widget.editType!=1){
      widget.dataMap['loadPlaceInfo'].length==1?
      isAddStart = false:isAddStart = true;
      widget.dataMap['unloadPlaceInfo'].length==1?
      isAddEnd = false:isAddEnd = true;
      startCitynameOne =widget.dataMap['loadPlaceInfo'][0]['city']+" "+widget.dataMap['loadPlaceInfo'][0]['county'];
      startAddressOne=[widget.dataMap['loadPlaceInfo'][0]['province'],widget.dataMap['loadPlaceInfo'][0]['city'],widget.dataMap['loadPlaceInfo'][0]['county']];
      startLocationOne={"lat":widget.dataMap['loadPlaceInfo'][0]['latitude'],"lng":widget.dataMap['loadPlaceInfo'][0]['longitude']};
      detailAddressOne=widget.dataMap['loadPlaceInfo'][0]['address'];
     if(  widget.dataMap['loadPlaceInfo'].length==2) {
       startAddressTwo = [widget.dataMap['loadPlaceInfo'][1]['province'], widget.dataMap['loadPlaceInfo'][1]['city'], widget.dataMap['loadPlaceInfo'][1]['county']];
       startLocationTwo={"lat":widget.dataMap['loadPlaceInfo'][1]['latitude'],"lng":widget.dataMap['loadPlaceInfo'][1]['longitude']};
       detailAddressTwo=widget.dataMap['loadPlaceInfo'][1]['address'];
     }
     endAddressOne=[widget.dataMap['unloadPlaceInfo'][0]['province'],widget.dataMap['unloadPlaceInfo'][0]['city'],widget.dataMap['unloadPlaceInfo'][0]['county']];
      if(  widget.dataMap['unloadPlaceInfo'].length==2)
        endAddressTwo=[widget.dataMap['unloadPlaceInfo'][1]['province'],widget.dataMap['unloadPlaceInfo'][1]['city'],widget.dataMap['unloadPlaceInfo'][1]['county']];
      endCitynameOne =widget.dataMap['unloadPlaceInfo'][0]['city']+" "+widget.dataMap['unloadPlaceInfo'][0]['county'];
      startCitycodeOne = [widget.dataMap['loadPlaceInfo'][0]['province'],widget.dataMap['loadPlaceInfo'][0]['city'],widget.dataMap['loadPlaceInfo'][0]['county']];
      endCitycodeOne = [widget.dataMap['unloadPlaceInfo'][0]['province'],widget.dataMap['loadPlaceInfo'][0]['city'],widget.dataMap['loadPlaceInfo'][0]['county']];
      endLocationOne={"lat":widget.dataMap['unloadPlaceInfo'][0]['latitude'],"lng":widget.dataMap['unloadPlaceInfo'][0]['longitude']};
      detailAddressThree=widget.dataMap['unloadPlaceInfo'][0]['address']==null?"":widget.dataMap['unloadPlaceInfo'][0]['address'];
      if(widget.dataMap['loadPlaceInfo'].length==2) {
        startCitynameTwo = widget.dataMap['loadPlaceInfo'][1]['city'] + " " + widget.dataMap['loadPlaceInfo'][1]['county'];
        startCitycodeTwo = [widget.dataMap['loadPlaceInfo'][1]['province'],widget.dataMap['loadPlaceInfo'][1]['city'],widget.dataMap['loadPlaceInfo'][1]['county']];
        startLocationTwo={"lat":widget.dataMap['loadPlaceInfo'][1]['latitude'],"lng":widget.dataMap['loadPlaceInfo'][1]['longitude']};

      }
      if(widget.dataMap['unloadPlaceInfo'].length==2) {
        endCitynameTwo = widget.dataMap['unloadPlaceInfo'][1]['city'] + " " + widget.dataMap['loadPlaceInfo'][1]['county'];
        endCitycodeTwo = [widget.dataMap['unloadPlaceInfo'][1]['province'],widget.dataMap['unloadPlaceInfo'][1]['city'],widget.dataMap['unloadPlaceInfo'][1]['county']];
        detailAddressFour=widget.dataMap['unloadPlaceInfo'][1]['address'];
        endLocationTwo={"lat":widget.dataMap['unloadPlaceInfo'][1]['latitude'],"lng":widget.dataMap['unloadPlaceInfo'][1]['longitude']};

      }
      invoiceType =widget.dataMap['invoiceType']+1;
        if(widget.dataMap['cargoInfo'][0]['cargoName']!=null)
          goodsMessage=widget.dataMap['cargoInfo'][0]['cargoName'];
      if(widget.dataMap['cargoInfo'][0]['packageType']!=null)
        goodsMessage=goodsMessage+","+widget.dataMap['cargoInfo'][0]['packageType'];
            if(widget.dataMap['cargoInfo'][0]['cargoWeight']!=null)
      goodsMessage=goodsMessage+","+widget.dataMap['cargoInfo'][0]['cargoWeight'].toString()+"吨";
      if(widget.dataMap['cargoInfo'][0]['cargoVolume']!=null)
        goodsMessage=goodsMessage+","+widget.dataMap['cargoInfo'][0]['cargoVolume'].toString()+"方";
      carLength=widget.dataMap['vehicleLength'].split(',');
      carType=widget.dataMap['vehicleModel'].split(',');
      goodsMessageList=[widget.dataMap['cargoInfo'][0]['cargoName'],widget.dataMap['cargoInfo'][0]['packageType'],widget.dataMap['cargoInfo'][0]['cargoWeight'].toString(),widget.dataMap['cargoInfo'][0]['cargoVolume'].toString()];
      dintanceStr= widget.dataMap['distance'].toString();
    }
  }
  void getUserInfo(){
    NoLoadinggetApiManager.getData(
      context,
      MyServiceUrl.getLoginUser,
      {},
          (responseData)  {
        if(responseData['data']['companyInfo']!=null){
          setState(() {
            companyName=responseData['data']['companyInfo']['name'];
            titleType=2;
            if(widget.editType!=1){
              titleType=1;
            }
          });
        }
      },
    );
  }
  void getCityList() async {
    String? token = await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));

    dio.get<String>(MyServiceUrl.header+'api/webapp/dev/cityDict/tree')
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(r.toString());

        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          setState(() {
            cityData = jsonMap['data'];
          });

        } else {}
        // 打印结果
        print('Code: $code');
      });
    }).catchError((error) {
      print(error);
    });
  }

//获取距离
  Future<void> getDistanceAction() async {

    String? token = await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio.get<String>("https://api.map.baidu.com/directionlite/v1/driving?origin=${startLocationOne['lat']},${startLocationOne['lng']}&destination=${endLocationOne['lat']},${endLocationOne['lng']}&ak=0t6rhRWUGmqtbsMRMBVSqzbBwBrCzXLj")
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(r.toString());
        // 获取code和data
        String code = jsonMap['status'].toString();
        if (code == "0") {
          setState(() {
            List list =jsonMap['result']['routes'];
            dintanceStr = list[0]['distance'].toString();
          });
        } else {

        }
        // 打印结果
        print('Code: $code');
      });
    }).catchError((error) {
      print(error);
    });

  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return  Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        leading: IconButton(icon: Icon(Icons.arrow_back_ios,color: Colors.black,),onPressed: (){Navigator.pop(context);},),
        centerTitle: true,
        backgroundColor: Colors.white,
        title:Text(widget.editType==2||widget.editType==4?"编辑货源":"发布货源",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w300),),


      ),
      body: sendType==2?PublishEnterpriseGoods(): Column(
        children: [
          Expanded(child: ListView(
            children: [
              if(titleType==2)
              Container(
              decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(10))),
          margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w),
          padding: EdgeInsets.only(left: 15.w,right: 15.w,bottom: 10.h,top: 10.h),
          child:Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
             Text("企业名称",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
             Text(companyName,style: TextStyle(color: Colors.black,fontSize: 13.sp),),
            ],
          )),
              Container(
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10))),
                margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w),
                padding: EdgeInsets.only(left: 15.w,right: 10.w,bottom: 10.h,top: 10.h),
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        RichText(
                          text: TextSpan(

                            children: <TextSpan>[
                              TextSpan(
                                text: '*',
                                style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp ),
                              ),
                              TextSpan(
                                text: '发票类型',
                                style: TextStyle(color: Colors.black,fontSize: 14.sp),
                              ),
                            ],
                          ),
                        ),
                        GestureDetector(
                          child: Row(
                            children: [
                              Text(invoiceType==1?"不开发票": "专票",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                              Icon(Icons.keyboard_arrow_right,color: MyColors.hintColor,),
                            ],
                          ),
                          onTap: ()async{
                            final result = await  showModalBottomSheet(context: context,
                                isScrollControlled:true,
                                isDismissible: false, // 设置为 false，点击外部区域不关闭
                                enableDrag: false, // 设置为 false，禁用上滑手势关闭
                                builder: (BuildContext context)
                                {
                                  return  InvoiceTypeSheet(invoiceType: invoiceType,);
                                });
                            if (result != null) {
                              setState(() {
                                invoiceType = result;
                              });
                            }
                          },
                        ),
                      ],
                    ),
                    if(invoiceType==1)SizedBox(height: 8.h,),
                    if(invoiceType==1)Text("注：您未选择平台代开发票，如需发票，请自行与司机商议",style: TextStyle(color: MyColors.themeColor,fontSize: 12.sp),),
                  ],
                ),


              ),
              Container(
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10))),
                margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w),
                padding: EdgeInsets.only(left: 20.w,right:15.w ,top: 25.h,bottom: 25.h),
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [

                        Row(
                          children: [
                            Image.asset("lib/Images/OrderList/装货点icon.png",width: 20.w,height: 20.h,),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Container(
                                  width:screenSize.width-120.w,
                                  padding: EdgeInsets.only(left: 10.w),
                                  child:   GestureDetector(
                                    child:Text(startCitynameOne!=""?startCitynameOne: "必填，请选择装货省市区",style: TextStyle(color:startCitynameOne!=""?Colors.black: MyColors.textColor,fontSize: 14.sp),),
                                    onTap: ()async{
                                      final result = await  showModalBottomSheet(context: context,
                                          isScrollControlled:true,
                                          isDismissible: false, // 设置为 false，点击外部区域不关闭
                                          enableDrag: false, // 设置为 false，禁用上滑手势关闭
                                          builder: (BuildContext context)
                                          {

                                            return chooseCitySheet(chooseType: 1,cityData: cityData, chooseCityList: startAddressOne,chooseCodeList: startCitycodeOne,);
                                          });
                                      if (result != null) {
                                        setState(() {
                                          print(result);
                                          startCitynameOne = result[0]+" "+result[1]+" "+result[2];
                                          startCitycodeOne =[result[3],result[4],result[5]];
                                          startAddressOne=[result[0],result[1],result[2]];
                                        });
                                      }
                                    },
                                  ),

                                ),

                                Divider(height: 10.h,color: Colors.black,),
                                Container(
                                  width:screenSize.width-120.w,
                                  padding: EdgeInsets.only(left: 10.w),
                                  child:   GestureDetector(
                                    child:Text(detailAddressOne!=""?detailAddressOne:"必填，请填写详细地址",overflow: TextOverflow.clip,style: TextStyle(color: detailAddressOne!=""?Colors.black:MyColors.hintColor,fontSize: 14.sp),),
                                    onTap: ()async{
                                      final result = await  Navigator.push( context, FadeRoute(page:LoadingAddressView(addressType: 1, query: startAddressOne.isNotEmpty?startAddressOne[1]:"",)));
                                      if(result!=null){
                                        setState(() {
                                          print(result);
                                          startCitynameOne=result['province']+" "+result['city']+" "+result['district'];
                                          startCitycodeOne=[result['adcode'].substring(0, 2)+"0000",result['adcode'].substring(0, 4)+"00",result['adcode']];
                                          startAddressOne=[result['province'],result['city'],result['district']];
                                          detailAddressOne=result['address'];
                                          startLocationOne=result['location'];
                                          print(startCitycodeOne);
                                          if(detailAddressOne!=""&&detailAddressThree!=""){
                                            getDistanceAction();
                                          }
                                        });

                                      }
                                    },
                                  ),

                                ),


                              ],
                            )
                          ],
                        ),
                        isAddStart ==false?
                        IconButton(onPressed: (){
                          setState(() {
                            isAddStart=true;
                          });
                        }, icon: Icon(Icons.add_circle_outline,color: MyColors.textColor,))
                            :SizedBox(width: 10.w,),
                      ],
                    ),
                    Divider(height: 20.h,color: MyColors.backgreyColor,),
                    if (isAddStart==true)
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            children: [
                              Image.asset("lib/Images/OrderList/装icon.png",width: 20.w,height: 10.h,),
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Container(
                                    width:screenSize.width-120.w,
                                    padding: EdgeInsets.only(left: 10.w),
                                    child:   GestureDetector(
                                      child:Text(startCitynameTwo!=""?startCitynameTwo: "必填，请选择装货省市区",style: TextStyle(color:startCitynameTwo!=""?Colors.black: MyColors.textColor,fontSize: 14.sp),),
                                      onTap: ()async{
                                        final result = await  showModalBottomSheet(context: context,
                                            isScrollControlled:true,
                                            isDismissible: false, // 设置为 false，点击外部区域不关闭
                                            enableDrag: false, // 设置为 false，禁用上滑手势关闭
                                            builder: (BuildContext context)
                                            {
                                              return chooseCitySheet(chooseType: 2,cityData: cityData,chooseCityList: startAddressTwo,chooseCodeList: startCitycodeTwo,);
                                            });
                                        if (result != null) {
                                          setState(() {
                                            startCitynameTwo= result[0]+" "+result[1]+" "+result[2];
                                            startCitycodeTwo =[result[3],result[4],result[5]];
                                            startAddressTwo=[result[0],result[1],result[2]];
                                          });
                                        }
                                      },
                                    ),
                                  ),
                                  Divider(height: 10.h,color: MyColors.backgreyColor,),
                                  Container(
                                    width:screenSize.width-120.w,
                                    padding: EdgeInsets.only(left: 10.w),
                                    child:   GestureDetector(
                                      child:Text(detailAddressTwo!=""?detailAddressTwo:"必填，请填写详细地址",overflow: TextOverflow.clip,style: TextStyle(color: detailAddressTwo!=""?Colors.black:MyColors.hintColor,fontSize: 14.sp),),
                                      onTap: ()async{
                                        final result = await  Navigator.push( context, FadeRoute(page:LoadingAddressView(addressType: 2, query: startAddressTwo.isNotEmpty?startAddressTwo[1]:"",)));
                                        if(result!=null){
                                          setState(() {
                                            startCitynameTwo=result['province']+" "+result['city']+" "+result['district'];
                                            startCitycodeTwo=[result['adcode'].substring(0, 2)+"0000",result['adcode'].substring(0, 4)+"00",result['adcode']];
                                            startAddressTwo=[result['province'],result['city'],result['district']];
                                            detailAddressTwo=result['address'];
                                            startLocationTwo=result['location'];
                                          });

                                        }
                                      },
                                    ),

                                  ),

                                ],
                              )

                            ],
                          ),

                          IconButton(onPressed: (){
                            setState(() {
                              isAddStart=false;
                            });
                          }, icon: Icon(Icons.remove_circle_outline,color: MyColors.textColor,)),
                        ],
                      ),
                    if (isAddStart==true)
                      Divider(height: 20.h,color: MyColors.backgreyColor,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Image.asset("lib/Images/OrderList/卸货点icon.png",width: 20.w,height: 20.h,),

                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Container(
                                  width:screenSize.width-120.w,
                                  padding: EdgeInsets.only(left: 10.w),
                                  child:   GestureDetector(
                                    child:Text(endCitynameOne!=""?endCitynameOne: "必填，请选择卸货省市区",style: TextStyle(color:endCitynameOne!=""?Colors.black: MyColors.textColor,fontSize: 14.sp),),
                                    onTap: ()async{
                                      final result = await  showModalBottomSheet(context: context,
                                          isScrollControlled:true,
                                          isDismissible: false, // 设置为 false，点击外部区域不关闭
                                          enableDrag: false, // 设置为 false，禁用上滑手势关闭
                                          builder: (BuildContext context)
                                          {
                                            return chooseCitySheet(chooseType: 3,cityData: cityData,chooseCityList: endAddressOne,chooseCodeList: endCitycodeOne,);
                                          });
                                      if (result != null) {
                                        setState(() {
                                          endCitynameOne = result[0]+" "+result[1]+" "+result[2];
                                          endCitycodeOne =[result[3],result[4],result[5]];
                                          endAddressOne=[result[0],result[1],result[2]];
                                        });
                                      }
                                    },
                                  ),

                                ),
                       
                                Divider(height: 10.h,color: MyColors.backgreyColor,),

                                Container(
                                  width:screenSize.width-120.w,
                                  padding: EdgeInsets.only(left: 10.w),
                                  child:   GestureDetector(
                                    child:Text(detailAddressThree!=""?detailAddressThree:"必填，请填写详细地址",overflow: TextOverflow.clip,style: TextStyle(color: detailAddressThree!=""?Colors.black:MyColors.hintColor,fontSize: 14.sp),),
                                    onTap: ()async{
                                      final result = await  Navigator.push( context, FadeRoute(page:LoadingAddressView(addressType: 2, query: endAddressOne.isNotEmpty?endAddressOne[1]:"",)));
                                      if(result!=null){
                                        setState(() {
                                          endCitynameOne=result['province']+" "+result['city']+" "+result['district'];
                                          endCitycodeOne=[result['adcode'].substring(0, 2)+"0000",result['adcode'].substring(0, 4)+"00",result['adcode']];
                                          endAddressOne=[result['province'],result['city'],result['district']];
                                          detailAddressThree=result['address'];
                                          endLocationOne=result['location'];
                                          if(detailAddressOne!=""&&detailAddressThree!=""){
                                            getDistanceAction();
                                          }
                                        });

                                      }
                                    },
                                  ),

                                ),

    // ),
    ],
                            ),
                          ],
                        ),
                        isAddEnd==false?
                        IconButton(onPressed: (){
                          setState(() {
                            isAddEnd=true;
                          });
                        }, icon: Icon(Icons.add_circle_outline,color: MyColors.textColor,))
                            :SizedBox(width: 10.w,),
                      ],
                    ),
                    if (isAddEnd==true)
                      Divider(height: 20.h,color: MyColors.backgreyColor,),
                    if (isAddEnd==true)
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            children: [
                              Image.asset("lib/Images/OrderList/卸icon.png",width:20.w,height: 10.h,),
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  Container(
                                    width:screenSize.width-120.w,
                                    padding: EdgeInsets.only(left: 10.w),
                                    child:   GestureDetector(
                                      child:Text(endCitynameTwo!=""?endCitynameTwo: "必填，请选择卸货省市区",style: TextStyle(color:endCitynameTwo!=""?Colors.black: MyColors.textColor,fontSize: 14.sp),),
                                      onTap: ()async{
                                        final result = await  showModalBottomSheet(context: context,
                                            isScrollControlled:true,
                                            isDismissible: false, // 设置为 false，点击外部区域不关闭
                                            enableDrag: false, // 设置为 false，禁用上滑手势关闭
                                            builder: (BuildContext context)
                                            {
                                              return chooseCitySheet(chooseType: 4,cityData: cityData,chooseCityList: endAddressTwo, chooseCodeList: endCitycodeTwo,);
                                            });
                                        if (result != null) {
                                          setState(() {
                                            endCitynameTwo = result[0]+" "+result[1]+" "+result[2];
                                            endCitycodeTwo =[result[3],result[4],result[5]];
                                            endAddressTwo=[result[0],result[1],result[2]];
                                          });
                                        }
                                      },
                                    ),

                                  ),
                                  
                                  Divider(height: 10.h,color: MyColors.backgreyColor,),
                                Container(
                                width:screenSize.width-120.w,
                                padding: EdgeInsets.only(left: 10.w),
                                child:   GestureDetector(
                                  child:Text(detailAddressFour!=""?detailAddressFour:"必填，请填写详细地址",overflow: TextOverflow.clip,style: TextStyle(color: detailAddressFour!=""?Colors.black:MyColors.hintColor,fontSize: 14.sp),),
                                onTap: ()async{
                                  final result = await  Navigator.push( context, FadeRoute(page:LoadingAddressView(addressType: 2, query: endAddressTwo.isNotEmpty?endAddressTwo[1]:"",)));
                                  if(result!=null){
                                    setState(() {
                                      endCitynameTwo=result['province']+" "+result['city']+" "+result['district'];
                                      endCitycodeTwo=[result['adcode'].substring(0, 2)+"0000",result['adcode'].substring(0, 4)+"00",result['adcode']];
                                      endAddressTwo=[result['province'],result['city'],result['district']];
                                      detailAddressFour=result['address'];
                                      endLocationTwo=result['location'];
                                    });

                                  }
                                },
                                ),

                              ),
                                ],
                              )
                            ],
                          ),

                          IconButton(onPressed: (){
                            setState(() {
                              isAddEnd=false;
                            });
                          }, icon: Icon(Icons.remove_circle_outline,color: MyColors.textColor,)),
                        ],
                      ),
                  ],
                ),
              ),
              Container(
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10))),
                margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w),
                padding: EdgeInsets.only(left: 15.w,right: 10.w,bottom: 15.h,top: 15.h),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    RichText(
                      text: TextSpan(

                        children: <TextSpan>[
                          TextSpan(
                            text: '*',
                            style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp ),
                          ),
                          TextSpan(
                            text: '货物信息',
                            style: TextStyle(color: Colors.black,fontSize: 14.sp),
                          ),
                        ],
                      ),
                    ),
                    GestureDetector(
                      child:    Row(
                        children: [
                          goodsMessage!=""?
                          Text(goodsMessage,style: TextStyle(color: Colors.black,fontSize: 14.sp),):
                          Text("必填，请输入货物信息",style: TextStyle(color: MyColors.hintColor,fontSize: 14.sp),),
                          Icon(Icons.keyboard_arrow_right,color: MyColors.hintColor,),
                        ],
                      ),
                      onTap: ()async{
                        final result = await     Navigator.push( context, FadeRoute(page: goodsMessageList!=null?CargoInformation(goodsName:goodsMessageList?[0], packType: goodsMessageList?[1], Weight:  goodsMessageList?[2], Volume:  goodsMessageList?[3], chooseType: 1,) :
                          CargoInformation(goodsName: '', packType: '', Weight: '', Volume: '', chooseType: 1,)));
                        // 在这里处理从下一个页面返回的值
                        if (result != null) {
                          print('从下一个页面返回的值：$result');
                          print(result[0]);
                          setState(() {
                            goodsMessage =result[0];
                            goodsMessageList=[result[1],result[2],result[3],result[4]];
                            if (result[5]!="")
                              parentDictValue =result[5];
                          });
                        }
                      },
                    ),

                  ],
                ),
              ),
              Container(
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10))),
                margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w),
                padding: EdgeInsets.only(left: 15.w,right: 10.w,bottom: 15.h,top: 15.h),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    RichText(
                      text: TextSpan(

                        children: <TextSpan>[
                          TextSpan(
                            text: '*',
                            style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp ),
                          ),
                          TextSpan(
                            text: '车长车型',
                            style: TextStyle(color: Colors.black,fontSize: 14.sp),
                          ),
                        ],
                      ),
                    ),
                    GestureDetector(
                      child:    Row(
                        children: [
                          !carLength.isEmpty&&!carType.isEmpty?
                          Text(carLength.map((element) => '$element米').join(', ').replaceAll(" ", "")+"\n"+carType.join(', ').replaceAll(" ", ""),style: TextStyle(color: Colors.black,fontSize: 14.sp),):
                          Text("必填，请输入车长车型",style: TextStyle(color: MyColors.hintColor,fontSize: 14.sp),),
                          Icon(Icons.keyboard_arrow_right,color: MyColors.hintColor,),
                        ],
                      ),
                      onTap: ()async{
                        final result = await  showModalBottomSheet(context: context,
                            isScrollControlled:true,
                            isDismissible: false, // 设置为 false，点击外部区域不关闭
                            enableDrag: false, // 设置为 false，禁用上滑手势关闭
                            builder: (BuildContext context)
                            {
                              return  carLengthandTypeSheet(carLength: carLength, carType: carType,);
                            });
                        if (result != null) {
                          setState(() {
                            carLength = result[0];
                            carType=result[1];
                          });
                        }
                      },
                    ),
                  ],
                ),
              ),
            ],
          ),
          ),
          Container(
            height: 80.h,
            color: Colors.white,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                    height: 40.h ,
                    margin: EdgeInsets.only(left: 30.w,right: 30.w),
                    decoration: BoxDecoration(

                        color: Color.fromRGBO(231, 112, 27, 0.85),
                        borderRadius: BorderRadius.all(Radius.circular(30))),

                    width: double.infinity,


                    child: TextButton(
                      child: Text("下一步",style: TextStyle(color: Colors.white,fontSize: 14.sp,fontWeight: FontWeight.w600),),

                      onPressed: () {
                        if (widget.editType != 1) {
                          widget.dataMap['loadPlaceInfo'][0]['city'] =
                          startAddressOne[1];
                          widget.dataMap['loadPlaceInfo'][0]['province'] =
                          startAddressOne[0];
                          widget.dataMap['loadPlaceInfo'][0]['county'] =
                          startAddressOne[2];
                          print("parentDictValue:$parentDictValue");
                          widget.dataMap['cargoInfo'][0]['cargoTypeCode'] =
                              parentDictValue;
                          // widget.dataMap['loadPlaceInfo'][0]['cityCode'] =
                          // startCitycodeOne[1];
                          // widget.dataMap['loadPlaceInfo'][0]['provinceCode'] =
                          // startCitycodeOne[0];
                          // widget.dataMap['loadPlaceInfo'][0]['countyCode'] =
                          // startCitycodeOne[2];
                          // if (!startAddressTwo.isEmpty) {
                          //   widget.dataMap['loadPlaceInfo'][1]['city'] =
                          //   startAddressTwo[1];
                          //   widget.dataMap['loadPlaceInfo'][1]['province'] =
                          //   startAddressTwo[0];
                          //   widget.dataMap['loadPlaceInfo'][1]['county'] =
                          //   startAddressTwo[2];
                          //   widget.dataMap['loadPlaceInfo'][1]['cityCode'] =
                          //   startCitycodeTwo[1];
                          //   widget.dataMap['loadPlaceInfo'][1]['provinceCode'] =
                          //   startCitycodeTwo[0];
                          //   widget.dataMap['loadPlaceInfo'][1]['countyCode'] =
                          //   startCitycodeTwo[2];
                          // }
                          // widget.dataMap['unloadPlaceInfo'][0]['city'] =
                          // startAddressOne[1];
                          // widget.dataMap['unloadPlaceInfo'][0]['province'] =
                          // startAddressOne[0];
                          // widget.dataMap['unloadPlaceInfo'][0]['county'] =
                          // startAddressOne[2];
                          // widget.dataMap['unloadPlaceInfo'][0]['cityCode'] =
                          // startCitycodeOne[1];
                          // widget.dataMap['unloadPlaceInfo'][0]['provinceCode'] =
                          // startCitycodeOne[0];
                          // widget.dataMap['unloadPlaceInfo'][0]['countyCode'] =
                          // startCitycodeOne[2];
                          // if (!endAddressTwo.isEmpty) {
                          //   widget.dataMap['unloadPlaceInfo'][1]['city'] =
                          //   endAddressTwo[1];
                          //   widget.dataMap['unloadPlaceInfo'][1]['province'] =
                          //   endAddressTwo[0];
                          //   widget.dataMap['unloadPlaceInfo'][1]['county'] =
                          //   endAddressTwo[2];
                          //   widget.dataMap['unloadPlaceInfo'][1]['cityCode'] =
                          //   endCitycodeTwo[1];
                          //   widget
                          //       .dataMap['unloadPlaceInfo'][1]['provinceCode'] =
                          //   endCitycodeTwo[0];
                          //   widget.dataMap['unloadPlaceInfo'][1]['countyCode'] =
                          //   endCitycodeTwo[2];
                          // }
                          widget.dataMap['invoiceType'] = invoiceType - 1;
                          widget.dataMap['cargoInfo'][0]['cargoWeight'] =
                          goodsMessageList?[2];
                          widget.dataMap['cargoInfo'][0]['cargoVolume'] =
                          goodsMessageList?[3];
                          widget.dataMap['cargoInfo'][0]['cargoName'] =
                          goodsMessageList?[0];
                          widget.dataMap['cargoInfo'][0]['packgeType'] =
                          goodsMessageList?[1];
                          // widget.dataMap['vehicleLength'] =
                          //     carLength?.join(', ');
                          // widget.dataMap['vehicleType'] = carType?.join(', ');
                        }
                        if (startAddressOne.length < 3) {
                          BrnToast.show("请填写装货地址", context);
                        } else if (endAddressOne.length < 3) {
                          BrnToast.show("请填写卸货地址", context);
                        } else if (goodsMessage == "") {
                          BrnToast.show("请填写货物信息", context);
                        } else if (carLength.isEmpty || carType.isEmpty) {
                          BrnToast.show("请填写车辆信息", context);
                        } else {
                          Navigator.push(context, FadeRoute(
                              page: PerfectGoods(goodsList: {
                                "category": 0,
                                "invoiceType": invoiceType - 1,
                                "loadPlaceInfo": [
                                  {
                                    "province": startAddressOne[0],
                                    "city": startAddressOne[1],
                                    "county": startAddressOne[2],
                                    "detailedAddress": detailAddressOne,
                                    "provinceCode": startCitycodeOne[0],
                                    "cityCode": startCitycodeOne[1],
                                    "countyCode": startCitycodeOne[2],
                                    "longitude": startLocationOne['lng'],
                                    "latitude": startLocationOne['lat'],
                                    "contact": "王帅",
                                    "contactPhone": 18888888888
                                  },
                                  if (!startAddressTwo.isEmpty){
                                    "province": startAddressTwo[0],
                                    "city": startAddressTwo[1],
                                    "county": startAddressTwo[2],
                                    "detailedAddress": detailAddressTwo,
                                    "provinceCode": startCitycodeTwo[0],
                                    "cityCode": startCitycodeTwo[1],
                                    "countyCode": startCitycodeTwo[2],
                                    "longitude": startLocationTwo['lng'],
                                    "latitude": startLocationTwo['lat'],
                                    "contact": "王帅",
                                    "contactPhone": 18888888888
                                  }
                                ],
                                "unloadPlaceInfo": [
                                  {
                                    "province": endAddressOne[0],
                                    "city": endAddressOne[1],
                                    "county": endAddressOne[2],
                                    "detailedAddress": detailAddressThree,
                                    "provinceCode": endCitycodeOne[0],
                                    "cityCode": endCitycodeOne[1],
                                    "countyCode": endCitycodeOne[2],
                                    // "longitude":endLocationOne['lng'],
                                    // "latitude": endLocationOne['lat'],
                                    "longitude": endLocationOne['lng'],
                                    "latitude": endLocationOne['lat'],
                                    "contact": "王帅",
                                    "contactPhone": 18888888888
                                  },
                                  if (!endAddressTwo.isEmpty) {
                                    "province": endAddressTwo[0],
                                    "city": endAddressTwo[1],
                                    "county": endAddressTwo[2],
                                    "detailedAddress": detailAddressFour,
                                    "provinceCode": endCitycodeTwo[0],
                                    "cityCode": endCitycodeTwo[1],
                                    "countyCode": endCitycodeTwo[2],
                                    "longitude": endLocationTwo['lng'],
                                    "latitude": endLocationTwo['lat'],
                                    // "longitude": "120.747303",
                                    // "latitude": "31.374582",
                                    "contact": "王帅",
                                    "contactPhone": 18888888888
                                  }
                                ],
                                "distance": dintanceStr,
                                "cargoInfo": [
                                  {
                                    "cargoWeight": goodsMessageList?[2],
                                    "cargoVolume": goodsMessageList?[3],
                                    "cargoName": goodsMessageList?[0],
                                    "packgeType": goodsMessageList?[1],
                                    "cargoTypeCode": parentDictValue,
                                  }
                                ],
                                "vehicleLength": carLength.join(', ').replaceAll(" ", ""),
                                "vehicleType": carType.join(', ').replaceAll(" ", ""),
                                "loadTimeDay": "",
                                "loadTimeHms": "",
                                "unLoadTimeDay": "",
                                "unLoadTimeHms": "",
                                "deposit": 0,
                                "depositType": 0,
                                "freight": 0,
                                "techServiceCharge": 0,
                                "elecProtocolCharge": 0,
                                "type": 0,
                                "remark": "",
                                "insurance": [],
                                "status": 0,
                              },
                                editType: widget.editType,
                                dataMap: widget.editType != 1
                                    ? widget.dataMap
                                    : {},
                              )));
                        }
                      }
                    )
                ),
              ],
            ),
          ),
        ],
      ),


    );

  }

  Map<String, dynamic>? findSelectedProvince() {
    return cityData.firstWhere(
          (province) => province['cityName'] == selectedProvince,
      orElse: () => null,
    );
  }

  Map<String, dynamic>? findSelectedCity() {
    return findSelectedProvince()?['children']?.firstWhere(
          (city) => city['cityName'] == selectedCity,
      orElse: () => null,
    );
  }

  Widget buildListViewOne(List<dynamic> dataList, Function(Map<String, dynamic>) onTap) {

    return ListView.builder(
      itemCount: dataList.length,
      itemBuilder: (context, index) {
        return
          ListTile(
            title: Text(dataList[index]['cityName'],style: TextStyle(
              color: index == selectedTileIndexone ? MyColors.themeColor : Colors.black,
            ),),
            onTap: () {

              selectedTileIndexone = index;
              print(selectedTileIndexone);
              onTap(dataList[index]);},
          );
      },
    );
  }
  Widget buildListViewTwo(List<dynamic> dataList, Function(Map<String, dynamic>) onTap) {

    return ListView.builder(
      itemCount: dataList.length,
      itemBuilder: (context, index) {
        return
          ListTile(
            title: Text(dataList[index]['cityName'],style: TextStyle(
              color: index == selectedTileIndextwo ? MyColors.themeColor : Colors.black,
            ),),
            onTap: () {
              setState(() {
                selectedTileIndextwo = index;
                print(selectedTileIndextwo);
                onTap(dataList[index]);
              });
             },
          );
      },
    );
  }
  Widget buildListViewThree(List<dynamic> dataList, Function(Map<String, dynamic>) onTap) {

    return ListView.builder(
      itemCount: dataList.length,
      itemBuilder: (context, index) {
        return
          ListTile(
            title: Text(dataList[index]['cityName'],style: TextStyle(
              color: index == selectedTileIndexthree ? MyColors.themeColor : Colors.black,
            ),),
            onTap: () {
              selectedTileIndexthree = index;
              print(selectedTileIndexthree);
              onTap(dataList[index]);},
          );
      },
    );
  }
}

class InvoiceTypeSheet extends StatefulWidget {
  const InvoiceTypeSheet({super.key, required this.invoiceType});
  final int invoiceType;
  @override
  State<InvoiceTypeSheet> createState() => _InvoiceTypeSheetState();
}

class _InvoiceTypeSheetState extends State<InvoiceTypeSheet> {
  int invoiceType=1;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    invoiceType=widget.invoiceType;
  }
  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(10))),
      height: 300.h,
      child: Column(
        children: [
          SizedBox(height: 15.h,),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              GestureDetector(
                child: Row(
                    children:[
                      SizedBox(width: 20.w,),
                      Text("取消",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                    ]
                ),
                onTap: (){
                  Navigator.pop(context);
                },
              ),
              Text("发票类型",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w600),),
              Row(
                children: [
                  GestureDetector(
                    child: Container(
                      width:50.w,
                      height:20.h,
                      decoration: BoxDecoration(
                          color: MyColors.themeColor,
                          borderRadius: BorderRadius.all(Radius.circular(20))),
                      child: Center(
                        child: Text("确认",style: TextStyle(color: Colors.white,fontSize: 14.sp),),
                      ),
                    ),
                    onTap: (){
                      Navigator.pop(context, invoiceType);
                    },
                  ),
                  SizedBox(width: 20.w,),

                ],
              ),

            ],
          ),
          SizedBox(height: 30.h,),
          Container(
            margin: EdgeInsets.only(left: 23.w,right: 23.w),
            padding: EdgeInsets.only(left: 12.w,right: 12.w,top: 10.h,bottom: 10.h),
            decoration: BoxDecoration(
                border: Border.all(
                  color: MyColors.backgreyColor,
                  width: 1.0.w,
                ),
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(10))),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text("不开发票",style: TextStyle(color:Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                SizedBox(height: 8.h,),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text("因此类订单不满足代开电子普票的要求，\n平台无法代开，请线下自行与司机沟通\n开票事宜",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp,)),
                    IconButton(onPressed: (){
                      setState(() {
                        invoiceType=1;
                      });
                    }, icon:invoiceType!=1? Icon(Icons.panorama_fish_eye,color: MyColors.textColor):Icon(Icons.check_circle,color: MyColors.themeColor,)),
                  ],
                )
              ],
            ),
          ),
          SizedBox(height: 10.h,),
          Container(
            margin: EdgeInsets.only(left: 23.w,right: 23.w),
            padding: EdgeInsets.only(left: 12.w,right: 12.w,top: 10.h,bottom: 10.h),
            decoration: BoxDecoration(
                border: Border.all(
                  color: MyColors.backgreyColor,
                  width: 1.0.w,
                ),
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(10))),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text("专票",style: TextStyle(color:Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                    SizedBox(width: 8.w,),
                    BrnTagCustom(
                      tagText: "专票",
                      fontSize: 12.sp,
                      fontWeight: FontWeight.w600,
                    )
                  ],
                ),
                SizedBox(height: 8.h,),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text("3分钟极速成交，可开专票做进项抵扣",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp,)),
                    IconButton(onPressed: (){
                      setState(() {
                        invoiceType=2;
                      });
                    }, icon:invoiceType!=2? Icon(Icons.panorama_fish_eye,color: MyColors.textColor,):Icon(Icons.check_circle,color: MyColors.themeColor,)),
                  ],
                )
              ],
            ),
          ),
        ],
      ),
    );
  }

}

class chooseCitySheet extends StatefulWidget {
  const chooseCitySheet({super.key, required this.chooseType, required this.cityData, required this.chooseCityList, required this.chooseCodeList});
 final int chooseType;
 final List cityData;
 final List chooseCityList;
  final List chooseCodeList;
  @override
  State<chooseCitySheet> createState() => _chooseCitySheetState();
}

class _chooseCitySheetState extends State<chooseCitySheet> {

  String selectedProvince = '';
  String selectedCity = '';
  String selectedDistrict = '';
  String selectedProvinceCode = '';
  String selectedCityCode = '';
  String selectedDistrictCode = '';
  // List cityData = [];

  String storedData = '';
  int selectedTileIndexone=-1;
  int selectedTileIndextwo=-1;
  int selectedTileIndexthree=-1;
  List checkCityList=[];
  List checkCityCodeList=[];
  String searchTerm = "";
  String proviceStr="";
  FocusNode focusNode = FocusNode();
  BrnSearchTextController scontroller = BrnSearchTextController();
  TextEditingController textController = TextEditingController();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    ///initState 中添加监听，记得销毁
    textController.addListener(() {
      if (focusNode.hasFocus) {
        if (!BrunoTools.isEmpty(textController.text)) {
          scontroller.isClearShow = true;
          scontroller.isActionShow = true;
        }
      }
    });
    focusNode.addListener(() {
      if (focusNode.hasFocus) {
        if (!BrunoTools.isEmpty(textController.text)) {
          scontroller.isClearShow = true;
        }
      }
    });
    // if(widget.chooseCityList.isNotEmpty){
    //   selectedProvince=widget.chooseCityList[0];
    //   selectedCity=widget.chooseCityList[1];
    //   selectedDistrictCode=widget.chooseCityList[2];
    //   selectedProvinceCode = widget.chooseCodeList[0];
    //    selectedCityCode = widget.chooseCodeList[1];
    //  selectedDistrictCode = widget.chooseCodeList[2];
    //
    //
    // }
  }
  List<String> findAllDistricts(Map<String, dynamic> city) {
    List<String> allDistricts = [];

    void collectDistricts(Map<String, dynamic> node) {
      if (node.containsKey('children') && node['children'] is List<dynamic>) {
        List<dynamic> children = node['children'];
        for (var child in children) {
          if (child is Map<String, dynamic>) {
            allDistricts.add(child['cityName']);
            collectDistricts(child);
          }
        }
      }
    }

    collectDistricts(city);
    return allDistricts;
  }

  List<String> findAllDistrictCodes(Map<String, dynamic> city) {
    List<String> allDistrictCodes = [];

    void collectDistrictCodes(Map<String, dynamic> node) {
      if (node.containsKey('children') && node['children'] is List<dynamic>) {
        List<dynamic> children = node['children'];
        for (var child in children) {
          if (child is Map<String, dynamic>) {
            allDistrictCodes.add(child['postalCode']);
            collectDistrictCodes(child);
          }
        }
      }
    }

    collectDistrictCodes(city);
    return allDistrictCodes;
  }

  Map<String, dynamic>? findCityAndPostalCode(List<dynamic> cities, String searchTerm) {
    for (var city in cities) {
      try {
        var cityMap = city as Map<String, dynamic>;
        if (cityMap['cityName'] == searchTerm) {
          return cityMap;
        } else if (cityMap['children'] != null && cityMap['children'] is List<dynamic>) {
          var result = findCityAndPostalCode(cityMap['children'], searchTerm);
          if (result != null) {
            return result;
          }
        }
      } catch (e) {
        // Handle type conversion exception
      }
    }
    return null;
  }
  String findProvinceByPostalCode(List<dynamic> cities, String postalCode) {
    Map<String, dynamic>? city = findCityByPostalCode(cities, postalCode);

    if (city != null) {
      // 如果找到的城市就是省份，直接返回
      if (city['level'] == '1') {
        return city['cityName'] ?? '';
      }

      String provinceName = findTopLevelParentProvince(cities, city);
      return provinceName;
    }

    return '';
  }

  String findTopLevelParentProvince(List<dynamic> cities, Map<String, dynamic> city) {
    String parentId = city['parentCity'] ?? '';

    // 递归查找省份
    if (parentId.isNotEmpty) {
      Map<String, dynamic>? parentCity = findCityById(cities, parentId);

      if (parentCity != null) {
        if (parentCity['level'] == '1') {
          return parentCity['cityName'] ?? '';
        } else {
          return findTopLevelParentProvince(cities, parentCity);
        }
      }
    }

    return '';
  }

  Map<String, dynamic>? findCityByPostalCode(List<dynamic> cities, String postalCode) {
    return cities.firstWhere(
          (city) => city is Map<String, dynamic> && city['postalCode'] == postalCode,
      orElse: () => null,
    );
  }

  Map<String, dynamic>? findCityById(List<dynamic> cities, String cityId) {
    return cities.firstWhere(
          (city) => city is Map<String, dynamic> && city['parentCity'] == cityId,
      orElse: () => null,
    );
  }
//重置后2位
  String resetLastTwoDigits(String postalCode) {
    if (postalCode.length >= 2) {
      return postalCode.substring(0, postalCode.length - 2) + '00';
    }
    return postalCode;
  }
//重置后3位
  String resetLastThreeDigits(String postalCode) {
    if (postalCode.length >= 3) {
      return postalCode.substring(0, postalCode.length - 3) + '000';
    }
    return postalCode;
  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return Container(
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(10))),
      height: 500.h,
      child: Column(
        children: [
          SizedBox(height: 10.h,),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              TextButton(onPressed: (){Navigator.pop(context);}, child:  Text("     取消     ",style: TextStyle(color: Colors.black,fontSize: 14.sp),),),

              Text(widget.chooseType==1||widget.chooseType==2 ?"选择装货地":widget.chooseType==4 ?"选择收货地址":"选择卸货地",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w600),),
              TextButton(onPressed: (){  if(selectedProvince==""){
                BrnToast.show("请选择省", context);
              }else if(selectedCity==""){
                BrnToast.show("请选择市", context);
              }else if(selectedDistrict==""){
                BrnToast.show("请选择区", context);
              }else{
                Navigator.pop(context, [selectedProvince,selectedCity,selectedDistrict,selectedProvinceCode,selectedCityCode,selectedDistrictCode]);
              }}, child:   Text("     确认     ",style: TextStyle(color:MyColors.themeColor,fontSize: 14.sp),),),



            ],
          ),
          Container(
            height: 40.h,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(10)),
            ),
            child: GestureDetector(
              onTap: () {
                FocusScope.of(context).requestFocus(focusNode);
              },
              child: AbsorbPointer(
                absorbing: true,
                child: BrnSearchText(
                  focusNode: focusNode,
                  controller: textController,
                  searchController: scontroller..isActionShow = false,
                  innerColor:MyColors.backgreyColor,
                  borderRadius:BorderRadius.all(const Radius.circular(10.0)),
                  hintText:"搜索城市名称",
                  onTextClear: () {
                    debugPrint('sss');
                    setState(() {
                      checkCityList=[];
                      checkCityCodeList=[];
                    });
                    return false;
                  },
                  autoFocus: false, // 设置为false，不自动获取焦点
                  onActionTap: () {
                    scontroller.isClearShow = false;
                    scontroller.isActionShow = false;
                    focusNode.unfocus();
                    // BrnToast.show('取消', context);
                    setState(() {});
                  },
                  onTextCommit: (text) {
                    BrnToast.show('提交内容 : $text', context);
                  },
                  onTextChange: (text) {
                    NoLoadinggetApiManager.getData(
                      context, // 上下文对象，用于显示提示信息等
                      'api/system/dev/cityDict/geyByKey', // 您的API端点
                      {"key":text}, // 查询参数，如果没有可以传递null
                          (responseData)  {
                        setState(() {

                           for (var item in responseData['data']) {

                                        checkCityList.add(item["fullName"]);
                                        checkCityCodeList.add(item["postalCode"]);
                           }
                           // for (String str in responseData['data']) {
                           //   // 判断字符串中 '-' 的个数
                           //   List<String> parts = str.split('-');
                           //   int count = parts.length - 1; // '-' 的个数
                           //
                           //   // 如果有两个以上的 '-'，则保留该字符串
                           //   if (count < 2) {
                           //     checkCityList.remove(str);
                           //   }
                           // }
                        });
                      },
                    );
                    // List<dynamic> cityData = MyCityListData.CityList;
                    // searchTerm = text;
                    // Map<String, dynamic>? city = findCityAndPostalCode(cityData, searchTerm);
                    // String province = findProvinceByPostalCode(cityData, selectedProvinceCode);
                    // print('$searchTerm 所在的省份是 $province');
                    //
                    // if (city != null) {
                    //   List<String> allDistricts = findAllDistricts(city);
                    //   List<String> allDistrictCodes = findAllDistrictCodes(city);
                    //
                    //   if (allDistricts.isNotEmpty) {
                    //     print("All Districts: ${allDistricts.join(', ')}");
                    //     setState(() {
                    //       checkCityList=allDistricts;
                    //       searchTerm = text;
                    //       if (province!="") proviceStr =province;
                    //     });
                    //   } else {
                    //     print("No districts found");
                    //   }
                    //
                    //   if (allDistrictCodes.isNotEmpty) {
                    //     print("All District Codes: ${allDistrictCodes.join(', ')}");
                    //
                    //     setState(() {
                    //       checkCityCodeList =allDistrictCodes;
                    //       searchTerm = text;
                    //     });
                    //   } else {
                    //     print("No district codes found");
                    //   }
                    // } else {
                    //   print("City not found");
                    // }
                    // BrnToast.show('输入内容 : $text', context);
                  },
                ),
              ),
            ),
          ),
          SizedBox(height: 10.h,),
         !checkCityList.isEmpty&&checkCityList.length<27?
         Container(
           height: 240.h,
           color: Colors.white,
           padding: EdgeInsets.only(top: 8.h),
           child: ListView.builder(
               itemCount: checkCityList.length,
               itemBuilder: (BuildContext context, int index) {
                 return Container(
                   padding: EdgeInsets.only(left: 8.w,right: 8.w),
                   child: Column(
                     children: [
                       GestureDetector(
                         child:Row(
                           mainAxisAlignment: MainAxisAlignment.spaceBetween,
                           children: [
                             Row(
                               children: [
                                 Text(checkCityList[index],style: TextStyle(color:Colors.black,fontSize: 14.sp),),
                               ],
                             ),

                           ],
                         ),
                         onTap: (){
                           setState(() {
                             List<String> parts = checkCityList[index].split('-');
                             int tag = checkCityList[index].indexOf('-');
                             int count = parts.length - 1; // 分隔后的列表长度减去1就是 '-' 的个数
                             if (count == 2) {
                               selectedProvince = parts[0];
                               selectedCity = parts[1];
                               selectedDistrict = parts[2];
                               selectedProvinceCode=checkCityCodeList[index].substring(0, 2)+"0000";
                               selectedCityCode=checkCityCodeList[index].substring(0, 4)+"00";
                               selectedDistrictCode=checkCityCodeList[index];
                             } else if (count == 1) {
                               selectedProvince = parts[0];
                               selectedCity = parts[1];
                             } else {
                               selectedProvince = checkCityList[index];
                             }
                          // selectedCity=searchTerm;
                          // selectedDistrict= checkCityList[index];
                          // selectedCityCode=resetLastTwoDigits(checkCityCodeList[index]);
                          // selectedProvinceCode=resetLastThreeDigits(checkCityCodeList[index]);
                          // selectedDistrictCode=checkCityCodeList[index];
                          // selectedProvince=findProvinceByPostalCode(MyCityListData.CityList, selectedProvinceCode);
                          // print("pcode:$selectedProvince,citycode:$selectedCity,concode:$selectedDistrict");
                          // print("pcode:$selectedProvinceCode,citycode:$selectedCityCode,concode:$selectedDistrictCode");
                           });
                           Navigator.pop(context, [selectedProvince,selectedCity,selectedDistrict,selectedProvinceCode,selectedCityCode,selectedDistrictCode]);
                         },
                       ),

                       Divider(height: 16.h,color: MyColors.backgreyColor,),
                     ],
                   ),
                 );
               }
           ),

         )
          :Container(
            width: screenSize.width,
            height: 380.h,
            child:   Row(
              children: [

                // 显示省份列表
                Expanded(
                  child:   Container(
                    color: MyColors.backgreyColor,
                    child:   buildListViewOne(MyCityListData.CityList, (item) {
                      setState(() {
                        selectedProvince = item['cityName'];
                        selectedProvinceCode = item['postalCode'];
                        selectedCity = '';
                        selectedDistrict = '';
                        print(selectedProvinceCode);
                      });
                    }),
                  ),

                ),
                // 显示城市列表
                Expanded(
                  child: buildListViewTwo(
                    findSelectedProvince()?.containsKey('children') ?? false
                        ? findSelectedProvince()!['children']
                        : [],
                        (item) {
                      setState(() {
                        selectedCity = item['cityName'];
                        selectedDistrict = '';
                        selectedCityCode = item['postalCode'];
                        print(selectedCityCode);
                      });
                    },
                  ),
                ),
                // 显示区域列表
                Expanded(
                  child: buildListViewThree(
                    findSelectedCity()?.containsKey('children') ?? false
                        ? findSelectedCity()!['children']
                        : [],
                        (item) {
                      setState(() {
                        selectedDistrict = item['cityName'];
                        selectedDistrictCode = item['postalCode'];
                        print(selectedDistrictCode);
                      });
                    },
                  ),
                ),
              ],
            ),
          ),

        ],
      ),
    );
  }


  Map<String, dynamic> findParentCity(List<dynamic> cities, String parentCityId) {
    return cities
        .whereType<Map<String, dynamic>>()
        .firstWhere((city) => city['citytName'] == parentCityId, orElse: () => {});
  }

  Map<String, dynamic>? findSelectedProvince() {
    return MyCityListData.CityList.firstWhere(
          (province) => province['cityName'] == selectedProvince,
      orElse: () => <String, dynamic>{},
    );
  }

  Map<String, dynamic>? findSelectedCity() {
    return findSelectedProvince()?['children']?.firstWhere(
          (city) => city['cityName'] == selectedCity,
      orElse: () => <String, dynamic>{},
    );
  }

  Widget buildListViewOne(List<dynamic> dataList, Function(Map<String, dynamic>) onTap) {
    return ListView.builder(
      itemCount: dataList.length,
      itemBuilder: (context, index) {
        return ListTile(
          title: Text(
            dataList[index]['cityName'],
            style: TextStyle(fontSize: 14.sp,
              color: index == selectedTileIndexone ||(widget.chooseCityList.isNotEmpty &&widget.chooseCityList[0]== dataList[index]['cityName'])? MyColors.themeColor : Colors.black
            ),
          ),
          onTap: () {
            selectedTileIndexone = index;
            print(selectedTileIndexone);
            onTap(dataList[index]);
          },
        );
      },
    );
  }

  Widget buildListViewTwo(List<dynamic> dataList, Function(Map<String, dynamic>) onTap) {
    return ListView.builder(
      itemCount: dataList.length,
      itemBuilder: (context, index) {
        return ListTile(
          title: Text(
            dataList[index]['cityName'],
            style: TextStyle(fontSize: 14.sp,
              color: index == selectedTileIndextwo||(widget.chooseCityList.isNotEmpty &&widget.chooseCityList[1]== dataList[index]['cityName']) ? MyColors.themeColor : Colors.black,
            ),
          ),
          onTap: () {
            selectedTileIndextwo = index;
            print(selectedTileIndextwo);
            onTap(dataList[index]);
          },
        );
      },
    );
  }

  Widget buildListViewThree(List<dynamic> dataList, Function(Map<String, dynamic>) onTap) {
    return ListView.builder(
      itemCount: dataList.length,
      itemBuilder: (context, index) {
        return ListTile(
          title: Text(
            dataList[index]['cityName'],
            style: TextStyle(fontSize: 14.sp,
              color: index == selectedTileIndexthree||(widget.chooseCityList.isNotEmpty &&widget.chooseCityList[2]== dataList[index]['cityName']) ? MyColors.themeColor : Colors.black,
            ),
          ),
          onTap: () {
            selectedTileIndexthree = index;
            print(selectedTileIndexthree);
            onTap(dataList[index]);
          },
        );
      },
    );
  }
}

class carLengthandTypeSheet extends StatefulWidget {
  const carLengthandTypeSheet({super.key, required this.carLength, required this.carType});
  final List carLength;
  final List carType;
  @override
  State<carLengthandTypeSheet> createState() => _carLengthandTypeSheetState();
}

class _carLengthandTypeSheetState extends State<carLengthandTypeSheet> {

  List<String> lengthList = [
    "1.8", "2.7", "3.8", "4.2", "5", "6.2", "6.8", "7.7", "8.2", "8.7", "9.6",
    "11.7", "12.5", "13", "13.7", "15", "16", "17.5"
  ];
  List<String> carTypeList = [
    "平板", "高栏", "厢式", "集装箱", "自卸", "冷藏", "保温",
    "高低板", "面包车", "棉被车", "爬梯车", "飞翼车", "依维柯"
  ];
  // List carLength=[];
  //
  // List carType=[];
  @override
  Widget build(BuildContext context) {
    return Container(
      height:550.h,
      padding: EdgeInsets.only(top: 15.h),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(10))),
      child: ListView(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              TextButton(onPressed: (){ Navigator.pop(context);}, child:  Text("取消       ",style: TextStyle(color: Colors.black,fontSize: 14.sp),)),

              Text("车长车型",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w600),),
              TextButton(onPressed: (){  if(widget.carType.length<4&&widget.carLength.length<4)
                Navigator.pop(context,[widget.carLength,widget.carType]);
              else
                BrnToast.show("最多选择3个车长、车型", context);}, child: Text("       确认",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),),
            ],
          ),
          SizedBox(height: 15.h,),
          Container(
            height: 34.h,
            color: Color.fromRGBO(251, 236, 228, 1),
            child: Center(
              child: Text("请根据实际货物运输需求合理选择车辆，避免超载超限",style: TextStyle(color: MyColors.themeColor,fontSize: 13.sp),
              ),
            ),
          ),
          SizedBox(height: 20.h,),
          Row(
            children: [
              SizedBox(width: 15.w,),
              Text("*",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
              Text("车长",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
              Text("（必填，最多3项）",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
            ],
          ),
          SizedBox(height: 8.h,),
         Center(
            // padding: const EdgeInsets.all(8.0),
            child: Wrap(
              spacing: 8.w, // 两个Container之间的水平间距
              runSpacing: 10, // 行与行之间的垂直间距
              children: lengthList.map((length) {
                bool? isSelected = widget.carLength.contains(length);
                return GestureDetector(
                  onTap: () {
                    // 处理点击事件
                    setState(() {
                      if (isSelected) {
                        // 如果已经被选中，则移除
                        widget.carLength.remove(length);
                      } else if (widget.carLength.length < 3) {
                        // 如果未被选中且未达到最大选择数量，则添加
                        widget. carLength.add(length);
                        print(widget.carLength);
                      }
                    });
                  },
                  child: Container(
                    width: 70.w, // Container宽度
                    height: 25.h, // Container高度，使其成为正方形
                    decoration: BoxDecoration(
                      color: isSelected ? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor, // 根据状态决定颜色
                      borderRadius: BorderRadius.circular(3.0), // 设置Container的圆角
                    ),
                    child: Center(
                      child: Text(
                        length,
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: isSelected ?MyColors.themeColor:Colors.black, // 文字颜色为白色
                        ),
                      ),
                    ),
                  ),
                );
              }).toList(),
            ),
          ),



          SizedBox(height: 8.h,),
          Row(
            children: [
              SizedBox(width: 15.w,),
              Text("*",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
              Text("车型",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
              Text("（必填，最多3项）",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
            ],
          ),
          SizedBox(height: 8.h,),

          Center(
            // padding: const EdgeInsets.all(8.0),
            child: Wrap(
              spacing: 8.w, // 两个Container之间的水平间距
              runSpacing: 10, // 行与行之间的垂直间距
              children: carTypeList.map((length) {
                bool? isSelected = widget.carType.contains(length);

                return GestureDetector(
                  onTap: () {
                    // 处理点击事件
                    setState(() {
                      if (isSelected) {
                        // 如果已经被选中，则移除
                        widget.carType.remove(length);
                      } else if (widget.carType.length < 3) {
                        // 如果未被选中且未达到最大选择数量，则添加
                        widget.carType.add(length);
                        print(widget.carType);
                      }
                    });
                  },
                  child: Container(
                    width: 70.w, // Container宽度
                    height: 25.h, // Container高度，使其成为正方形
                    decoration: BoxDecoration(
                      color: isSelected ? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor, // 根据状态决定颜色
                      borderRadius: BorderRadius.circular(3.0), // 设置Container的圆角
                    ),
                    child: Center(
                      child: Text(
                        length,
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: isSelected ?MyColors.themeColor:Colors.black, // 文字颜色为白色
                        ),
                      ),
                    ),
                  ),
                );
              }).toList(),
            ),
          ),

        ],
      ),
    );
  }
}
